// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskInput = document.getElementById('taskInput');
    const addTaskBtn = document.getElementById('addTaskBtn');
    const taskList = document.getElementById('taskList');
    const tasksCount = document.getElementById('tasksCount');
    const clearCompletedBtn = document.getElementById('clearCompleted');
    const filterBtns = document.querySelectorAll('.filter-btn');
    
    // 当前过滤状态
    let currentFilter = 'all';
    
    // 从本地存储加载任务
    let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
    
    // 初始化应用
    function init() {
        renderTasks();
        updateTasksCount();
        
        // 添加事件监听器
        addTaskBtn.addEventListener('click', addTask);
        taskInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                addTask();
            }
        });
        
        clearCompletedBtn.addEventListener('click', clearCompletedTasks);
        
        filterBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // 更新活动按钮状态
                filterBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                // 更新过滤状态并重新渲染
                currentFilter = this.dataset.filter;
                renderTasks();
            });
        });
    }
    
    // 添加新任务
    function addTask() {
        const taskText = taskInput.value.trim();
        
        if (taskText) {
            // 创建新任务对象
            const newTask = {
                id: Date.now(),
                text: taskText,
                completed: false,
                createdAt: new Date()
            };
            
            // 添加到任务数组
            tasks.push(newTask);
            
            // 保存到本地存储
            saveTasks();
            
            // 清空输入框
            taskInput.value = '';
            
            // 重新渲染任务列表
            renderTasks();
            updateTasksCount();
        }
    }
    
    // 渲染任务列表
    function renderTasks() {
        // 清空当前列表
        taskList.innerHTML = '';
        
        // 根据过滤状态获取任务
        let filteredTasks = tasks;
        if (currentFilter === 'active') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 如果没有任务，显示提示
        if (filteredTasks.length === 0) {
            const emptyMessage = document.createElement('li');
            emptyMessage.className = 'empty-list';
            emptyMessage.textContent = '暂无任务';
            taskList.appendChild(emptyMessage);
            return;
        }
        
        // 渲染任务
        filteredTasks.forEach(task => {
            const taskItem = document.createElement('li');
            taskItem.className = 'task-item';
            if (task.completed) {
                taskItem.classList.add('completed');
            }
            
            taskItem.innerHTML = `
                <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
                <span class="task-text">${task.text}</span>
                <button class="delete-btn">×</button>
            `;
            
            // 添加事件监听器
            const checkbox = taskItem.querySelector('.task-checkbox');
            checkbox.addEventListener('change', () => toggleTaskCompleted(task.id));
            
            const deleteBtn = taskItem.querySelector('.delete-btn');
            deleteBtn.addEventListener('click', () => deleteTask(task.id));
            
            taskList.appendChild(taskItem);
        });
    }
    
    // 切换任务完成状态
    function toggleTaskCompleted(taskId) {
        tasks = tasks.map(task => {
            if (task.id === taskId) {
                return {...task, completed: !task.completed};
            }
            return task;
        });
        
        saveTasks();
        renderTasks();
        updateTasksCount();
    }
    
    // 删除任务
    function deleteTask(taskId) {
        tasks = tasks.filter(task => task.id !== taskId);
        saveTasks();
        renderTasks();
        updateTasksCount();
    }
    
    // 清除已完成任务
    function clearCompletedTasks() {
        tasks = tasks.filter(task => !task.completed);
        saveTasks();
        renderTasks();
        updateTasksCount();
    }
    
    // 更新任务计数
    function updateTasksCount() {
        const totalTasks = tasks.length;
        const completedTasks = tasks.filter(task => task.completed).length;
        const remainingTasks = totalTasks - completedTasks;
        
        tasksCount.textContent = `${remainingTasks} 个待完成，${completedTasks} 个已完成`;
    }
    
    // 保存任务到本地存储
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 初始化应用
    init();
});